/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.common.query.expression;

import com.eelpo.common.util.BlankUtils;

/**
 * <pre>
 * 
 * 结果表达式
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class ResultExpression implements CompoundCriterion {

	private boolean useAlias;
	private String property;

	private ResultExpression(boolean useAlias, String property) {
		this.useAlias = useAlias;
		this.property = property;
	}

	public static ResultExpression getCountResultExpression() {
		return new ResultExpression(false, "COUNT(*)");
	}

	public static ResultExpression getCountResultExpression(String property) {
		return new ResultExpression(false, COUNT.concat("(").concat(property).concat(")"));
	}

	public static ResultExpression getDistinctExpression() {
		return new ResultExpression(false, DISTINCT);
	}

	public static ResultExpression getResultExpression(String property) {
		return new ResultExpression(true, property);
	}

	public static ResultExpression getResultInornateExpression(String property) {
		return new ResultExpression(false, property);
	}

	public static ResultExpression getResultExpression() {
		return new ResultExpression(false, null) {
			@Override
			public StringBuilder getJpql(StringBuilder jpql, String ailas) {
				if (BlankUtils.isBlank(ailas)) {
					throw new IllegalStateException("ailas is null or empty.");
				}

				return jpql.append(ailas).replace(jpql.length() - 1, jpql.length(), " ");
			}
		};
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.common.query.expression.CompoundCriterion#getJpql(java.lang
	 *      .StringBuilder )
	 */
	@Override
	public StringBuilder getJpql(StringBuilder jpql, String ailas) {
		if (useAlias) {
			jpql.append(ailas);
		}
		jpql.append(property);
		jpql.append(" ");
		return jpql;
	}
}
